'use strict'

import electron, { protocol, ipcMain, BrowserView, screen} from 'electron'
const { app, BrowserWindow, session } = electron;
import fs from 'fs'
import {createProtocol} from 'vue-cli-plugin-electron-builder/lib'

const path = require('path')
import installExtension, {VUEJS_DEVTOOLS} from 'electron-devtools-installer'

const isDevelopment = process.env.NODE_ENV !== 'production'


// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
    {scheme: 'app', privileges: {secure: true, standard: true}}
])
let viewMap = new Map();
let loginWin;
let exitWin = null;
let taskWin;
let win;
let viewTop;
let view1;
let viewRight;
let viewDashborder;
let whatsWin
let whatsView
//1登陆 2退出当前帐号
const userAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.61 Safari/537.36";
const Menu = electron.Menu

async function whatsViews(arg) {
    const {width, height} = screen.getPrimaryDisplay().workAreaSize

    whatsWin = new BrowserWindow({
        width: width, height: height, title: "BeezoomV3",
        // frame:false,
        resizable: false
    })
    whatsView = new BrowserView({
        webPreferences: {
            webSecurity: false,
            contextIsolation: false,
            preload: path.join(__dirname, process.env.WEBPACK_DEV_SERVER_URL ? 'preload.js' : "/../../src/store/preload.js"),
        }
    })

    whatsWin.addBrowserView(whatsView)
    whatsView.setBounds({x: 0, y: 0, width: width, height: height})

    whatsView.webContents.loadURL(arg)
    // whatsView.webContents.openDevTools()
    whatsView.webContents.addListener("did-finish-load", () => {
        const js = fs.readFileSync(process.env.WEBPACK_DEV_SERVER_URL ? 'src/store/wapi6.js' : __dirname + '/../../src/store/wapi6.js').toString();
        whatsView.webContents.executeJavaScript(js);
    });

    whatsWin.addListener("close", event => {
        console.log("== close whatsapp view ==");
        event.preventDefault()
        whatsWin.hide();
    })
}

async function twoViews() {
    const {width, height} = screen.getPrimaryDisplay().workAreaSize
    Menu.setApplicationMenu(null)
    win = new BrowserWindow({
        width: 800,
        height: 800,
        title: "BeezoomV3",
        resizable: false
    })

    viewDashborder = new BrowserView({
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false
        }
    })

    win.addBrowserView(viewDashborder)
    viewDashborder.setBounds({x: 0, y: 0, width: 800, height: 800})
    viewDashborder.webContents.session.clearStorageData()
    console.log(7878,process.env.WEBPACK_DEV_SERVER_URL);
    if (process.env.WEBPACK_DEV_SERVER_URL) {
        viewDashborder.webContents.loadURL(process.env.WEBPACK_DEV_SERVER_URL + "#/login")
        // viewDashborder.webContents.openDevTools()
    } else {
        createProtocol('app')
        viewDashborder.webContents.loadURL('app://./index.html#login')
    }
}

ipcMain.on('logout-dialog-remove', (event, arg) => {
    if (win !== null && typeof win !== "undefined") {
        win.close();
    }
    if (taskWin !== null && typeof taskWin !== "undefined") {
        taskWin.close();
    }

    if (exitWin !== null && typeof exitWin !== "undefined") {
        exitWin.close();
    }

    loginWin.show();
})

ipcMain.on('openWhatsapp', (event, arg) => {
    if (whatsWin == null) {
        whatsViews();
    } else{

        whatsWin.show();
        whatsView.webContents.reload();
    }
})

ipcMain.on('originalLanguage', (event, arg) => {
    // console.log("originalLanguage===",arg)
    content = arg.content
})

ipcMain.on('cancelUpdate', () => {
    if (loginWin !== null) {
        loginWin.close()
    }
})
ipcMain.on('asynchronous-message', (event, arg) => {
    //console.log("asynchronous-message=====", arg)
    const view = viewMap.get(arg);
    //执行js方法 触发right包含信息的更新
    view.webContents.executeJavaScript("window.WAPI.getCurrentChatIdV2()");
    win.setTopBrowserView(view)

})

ipcMain.on('showWhatsapp', (event, arg) => {
    console.log("=-==-=-=12312412412",arg)
    whatsViews(arg)
    win.destroy()

})

ipcMain.on('selectNewChat', (event, arg) => {
    //console.log("selectNewChat=====", arg)
    viewTop.webContents.send('selectNewChat', arg)
    const mobile = arg.whatsApp.slice(0, arg.whatsApp.length - 5);
    const js = "window.WAPI.openChat(" + mobile + ",'" + arg.wLanguage.toString() + "')"
    viewMap.get(arg.viewId).webContents.executeJavaScript(js);
    win.moveTop()
})

ipcMain.on('startNewChat', (event, arg) => {
    // if (whatsWin == null) {
    //     whatsViews()
    // } else {
    //     whatsWin.moveTop()
    // }
    const mobile = arg.phone;
    const text = arg.text ? arg.text : "hi";
    const js = "window.WAPI.openChat(" + mobile + ",'" + text + "')"
    whatsView.webContents.executeJavaScript(js);
    console.log(arg);
})

ipcMain.on('startNewChatAndSend', (event, arg) => {
    const id = arg.id;
    let replaceStr = arg.content.replace(/[\r\n]/g, "");
    const js = "window.WAPI.openChatAndSend('" + id + "','" + replaceStr + "')"
    whatsView.webContents.executeJavaScript(js);
})


ipcMain.on('timingOpenChatAndSend', (event, arg) => {
    // console.log("autoReplyConfig====", arg)
    let replaceStr = arg.content.replace(/[\r\n]/g, "");
    const js = "window.WAPI.openChatAndSend('" + arg.id + "','" + replaceStr + "')"

    viewMap.get(arg.viewId).webContents.executeJavaScript(js);
})

ipcMain.on('windowreload', (event, arg) => {
    whatsView.webContents.reload();
})


ipcMain.on('chatChange', (event, arg) => {
    //console.log("=====chat change======= ", arg);
    viewRight.webContents.send('chatChange', arg)
})

ipcMain.on('translateRequest', (event, arg) => {
    //console.log("=====translateRequest======= ", arg);
    viewRight.webContents.send('translateRequest', arg)
})
ipcMain.on('commonNotify', (event, arg) => {
    //console.log("=====commonNotify======= ", arg);
    viewTop.webContents.send('commonNotify', arg)
})

ipcMain.on('translateRequestRes', (event, arg) => {
    viewMap.get(arg.viewId).webContents.send('translateRes', {
        dataId: arg.dataId,
        result: arg.result
    })
})
ipcMain.on('LogoutRequest', (event, arg) => {
    viewTop.webContents.send('LogoutRequest', arg)
})


ipcMain.on('autoReplyConfig', (event, id, arg) => {
    //console.log("autoReplyConfig====", id, arg)
    const js = "window.WAPI.setAutoReplyConfig(" + JSON.stringify(arg) + ")"
    viewMap.get(id).webContents.executeJavaScript(js);
})


ipcMain.on('chatMessage', (event, arg) => {
    console.log("=====chatMessage======= ", arg);
    viewRight.webContents.send('chatMessage', arg)

})


ipcMain.on('updateAutoReplyStatus', (event, arg) => {
    //console.log("===updateAutoReplyStatus====", arg);
    const js = "window.WAPI.setAutoReplay(" + arg.status + ")"
    viewMap.get(arg.viewId).webContents.executeJavaScript(js);
})


// Quit when all windows are closed.
app.on('window-all-closed', () => {
    //console.log("== 退出electron ===");
    // On macOS it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    app.quit()
    // if (process.platform !== 'darwin') {
    // }
})

app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) twoViews()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
    session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {
        details.requestHeaders["User-Agent"] = userAgent;
        callback({ cancel: false, requestHeaders: details.requestHeaders });
    });

    if (isDevelopment && !process.env.IS_TEST) {
        // Install Vue Devtools
        try {
            await installExtension(VUEJS_DEVTOOLS)
        } catch (e) {
            //console.error('Vue Devtools failed to install:', e.toString())
        }
    }
    // loginViews()
    twoViews();
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
    if (process.platform === 'win32') {
        process.on('message', (data) => {
            if (data === 'graceful-exit') {
                app.quit()
            }
        })
    } else {
        process.on('SIGTERM', () => {
            app.quit()
        })
    }
}

ipcMain.on('chatLog', (event, arg) => {
    console.log("== chatLog ==", arg.message);
    viewRight.webContents.send("uploadImage", {
        sender: arg.message.from.user,
        receiver: arg.message.to.user,
        msg_content: arg.message.content,
        mimetype: arg.message.mimetype,
        whatsapp_stuff_use: arg.me,
        stuffCode:""
    });
})

ipcMain.on('saveToken', (event, arg) => {
    console.log("== saveToken ==", arg);
    viewRight.webContents.send("saveToken", arg);
})

ipcMain.on('uploadImageRes', (event, arg) => {
    console.log(6789, arg);
    const js = "window.WAPI.openChatAndSend('" + arg.from + "','" + arg.msg + "')"
    view1.webContents.executeJavaScript(js);
    const js2 = "window.WAPI.openChatAndSend('" + arg.middleGroup + "','" + arg.msg + "')"
    view1.webContents.executeJavaScript(js2);
})


